<template>
	<view class="login-container">
		<view class="login-card">
			<image class="logo" src="/static/logo.png"></image>
			<view class="system-title">后台管理系统</view>
			
			<!-- 登录方式切换 -->
			<view class="login-tabs">
				<view class="tab-item" :class="{ active: loginType === 'password' }" @click="loginType = 'password'">
					密码登录
				</view>
				<view class="tab-item" :class="{ active: loginType === 'code' }" @click="loginType = 'code'">
					验证码登录
				</view>
			</view>
			
			<!-- 密码登录 -->
			<block v-if="loginType === 'password'">
				<view class="input-item">
					<view class="input-label">账号</view>
					<input class="input" type="text" v-model="passwordLogin.username" placeholder="请输入用户名" />
				</view>
				
				<view class="input-item">
					<view class="input-label">密码</view>
					<input class="input" type="password" v-model="passwordLogin.password" placeholder="请输入密码" />
				</view>
			</block>
			
			<!-- 验证码登录 -->
			<block v-else>
				<view class="input-item">
					<view class="input-label">邮箱</view>
					<input class="input" type="text" v-model="codeLogin.email" placeholder="请输入邮箱" />
				</view>
				
				<view class="input-item">
					<view class="input-label">验证码</view>
					<view class="code-input-group">
						<input class="input code-input" type="text" v-model="codeLogin.code" placeholder="请输入验证码" />
						<button class="code-btn" :disabled="codeBtnDisabled" @click="handleSendCode">
							{{ codeBtnText }}
						</button>
					</view>
				</view>
			</block>
			
			<button class="login-btn" @click="handleLogin" :disabled="loading">
				<text v-if="!loading">登录</text>
				<view v-else class="loading"></view>
			</button>
			
			<view class="action-links">
				<text class="link" @click="goToForgotPassword">忘记密码?</text>
				<text v-if="!hasAdmin" class="link" @click="goToRegister">注册管理员</text>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/api/index.js';
	import { hasRole, isAdmin } from '@/utils/permission.js';
	
	export default {
		data() {
			return {
				loginType: 'password',  // 'password' 或 'code'
				passwordLogin: {
					username: '',
					password: ''
				},
				codeLogin: {
					email: '',
					code: ''
				},
				loading: false,
				codeBtnDisabled: false,
				codeBtnText: '发送验证码',
				codeTimer: null,
				countdown: 60,
				hasAdmin: true  // 默认假设已有管理员
			}
		},
		onLoad() {
			// 检查是否已经登录
			const token = uni.getStorageSync('token');
			if (token) {
				this.checkAdminRole();
			} else {
				// 检查系统是否已有管理员
				this.checkAdminExists();
			}
		},
		onUnload() {
			// 清除定时器
			if (this.codeTimer) {
				clearInterval(this.codeTimer);
				this.codeTimer = null;
			}
		},
		methods: {
			// 检查是否具有管理员权限
			checkAdminRole() {
				if (isAdmin()) {
					// 已有管理员权限，直接跳转到首页
					uni.reLaunch({
						url: '/pages/index/index'
					});
				} else {
					// 无管理员权限，清空认证信息
					uni.removeStorageSync('token');
					uni.removeStorageSync('userRoles');
					uni.showToast({
						title: '您没有管理员权限',
						icon: 'none'
					});
				}
			},
			
			// 检查是否已有管理员账号
			checkAdminExists() {
				api.auth.checkAdminExists().then(res => {
					// 后端返回的完整响应，取data字段作为结果
					this.hasAdmin = res.data;
					
					// 如果没有管理员账号，直接跳转到注册页
					if (!this.hasAdmin) {
						this.goToRegister();
					}
				}).catch(err => {
					uni.showToast({
						title: '检查管理员账号失败',
						icon: 'none'
					});
				});
			},
			
			// 处理登录
			handleLogin() {
				if (this.loginType === 'password') {
					this.loginByPassword();
				} else {
					this.loginByCode();
				}
			},
			
			// 密码登录
			loginByPassword() {
				if (!this.passwordLogin.username || !this.passwordLogin.password) {
					uni.showToast({
						title: '请输入用户名和密码',
						icon: 'none'
					});
					return;
				}
				
				this.loading = true;
				
				// 调用管理员登录接口
				api.auth.adminLogin({
					account: this.passwordLogin.username,
					password: this.passwordLogin.password
				}).then(res => {
					this.handleLoginSuccess(res);
				}).catch(err => {
					uni.showToast({
						title: err.message || '登录失败',
						icon: 'none'
					});
				}).finally(() => {
					this.loading = false;
				});
			},
			
			// 验证码登录
			loginByCode() {
				if (!this.codeLogin.email) {
					uni.showToast({
						title: '请输入邮箱',
						icon: 'none'
					});
					return;
				}
				
				if (!this.codeLogin.code) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					});
					return;
				}
				
				this.loading = true;
				
				// 调用验证码登录接口
				api.auth.adminLoginByCode({
					email: this.codeLogin.email,
					code: this.codeLogin.code
				}).then(res => {
					this.handleLoginSuccess(res);
				}).catch(err => {
					uni.showToast({
						title: err.message || '登录失败',
						icon: 'none'
					});
				}).finally(() => {
					this.loading = false;
				});
			},
			
			// 处理登录成功
			handleLoginSuccess(res) {
				// 检查是否有管理员角色
				if (hasRole('ROLE_ADMIN')) {
					uni.showToast({
						title: '登录成功',
						icon: 'success'
					});
					
					// 跳转到首页
					setTimeout(() => {
						uni.reLaunch({
							url: '/pages/index/index'
						});
					}, 1000);
				} else {
					// 无管理员权限
					uni.removeStorageSync('token');
					uni.removeStorageSync('userRoles');
					uni.showToast({
						title: '您没有管理员权限',
						icon: 'none'
					});
				}
			},
			
			// 发送验证码
			handleSendCode() {
				if (!this.codeLogin.email) {
					uni.showToast({
						title: '请输入邮箱',
						icon: 'none'
					});
					return;
				}
				
				// 邮箱格式验证
				if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(this.codeLogin.email)) {
					uni.showToast({
						title: '邮箱格式不正确',
						icon: 'none'
					});
					return;
				}
				
				this.codeBtnDisabled = true;
				
				// 调用发送验证码接口
				api.auth.sendLoginCode({
					email: this.codeLogin.email
				}).then(res => {
					uni.showToast({
						title: '验证码已发送',
						icon: 'success'
					});
					
					// 开始倒计时
					this.startCountdown();
				}).catch(err => {
					uni.showToast({
						title: err.message || '验证码发送失败',
						icon: 'none'
					});
					this.codeBtnDisabled = false;
				});
			},
			
			// 开始倒计时
			startCountdown() {
				this.countdown = 60;
				this.codeBtnText = `${this.countdown}秒后重试`;
				
				this.codeTimer = setInterval(() => {
					this.countdown--;
					this.codeBtnText = `${this.countdown}秒后重试`;
					
					if (this.countdown <= 0) {
						clearInterval(this.codeTimer);
						this.codeTimer = null;
						this.codeBtnText = '发送验证码';
						this.codeBtnDisabled = false;
					}
				}, 1000);
			},
			
			// 跳转到忘记密码页面
			goToForgotPassword() {
				uni.navigateTo({
					url: '/pages/login/forgot-password'
				});
			},
			
			// 跳转到注册页面
			goToRegister() {
				uni.navigateTo({
					url: '/pages/login/register'
				});
			}
		}
	}
</script>

<style>
	.login-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #f5f5f5;
		background-image: linear-gradient(135deg, #3f51b5 0%, #2196f3 100%);
	}
	
	.login-card {
		width: 80%;
		max-width: 400px;
		background-color: #fff;
		border-radius: 8px;
		padding: 30px;
		box-shadow: 0 2px 25px rgba(0, 0, 0, 0.2);
		display: flex;
		flex-direction: column;
		align-items: center;
	}
	
	.logo {
		width: 100px;
		height: 100px;
		margin-bottom: 20px;
	}
	
	.system-title {
		font-size: 24px;
		font-weight: bold;
		margin-bottom: 30px;
		color: #333;
	}
	
	.login-tabs {
		width: 100%;
		display: flex;
		border-bottom: 1px solid #eee;
		margin-bottom: 20px;
	}
	
	.tab-item {
		flex: 1;
		text-align: center;
		padding: 10px 0;
		position: relative;
		cursor: pointer;
		color: #666;
	}
	
	.tab-item.active {
		color: #3f51b5;
		font-weight: bold;
	}
	
	.tab-item.active:after {
		content: '';
		position: absolute;
		bottom: -1px;
		left: 20%;
		width: 60%;
		height: 2px;
		background-color: #3f51b5;
	}
	
	.input-item {
		width: 100%;
		margin-bottom: 20px;
	}
	
	.input-label {
		font-size: 14px;
		color: #666;
		margin-bottom: 5px;
	}
	
	.input {
		width: 100%;
		height: 40px;
		border: 1px solid #ddd;
		border-radius: 4px;
		padding: 0 10px;
		font-size: 14px;
		box-sizing: border-box;
	}
	
	.code-input-group {
		display: flex;
		gap: 10px;
	}
	
	.code-input {
		flex: 1;
	}
	
	.code-btn {
		width: 120px;
		height: 40px;
		background-color: #3f51b5;
		color: #fff;
		border-radius: 4px;
		font-size: 14px;
		padding: 0;
		line-height: 40px;
	}
	
	.code-btn:disabled {
		background-color: #9e9e9e;
	}
	
	.login-btn {
		width: 100%;
		height: 40px;
		background-color: #3f51b5;
		color: #fff;
		border-radius: 4px;
		font-size: 16px;
		margin-top: 10px;
		line-height: 40px;
	}
	
	.login-btn:disabled {
		background-color: #9e9e9e;
		cursor: not-allowed;
	}
	
	.loading {
		width: 20px;
		height: 20px;
		border: 2px solid #fff;
		border-radius: 50%;
		border-top: 2px solid transparent;
		animation: spin 1s linear infinite;
		margin: 0 auto;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	
	.action-links {
		width: 100%;
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
	}
	
	.link {
		color: #3f51b5;
		font-size: 14px;
		cursor: pointer;
	}
</style> 